import React from 'react';
import '../../static/setting/index.styl'
import moment from 'moment';
import {
  Icon,
  Button,
  Form,
  Input,
  message,
  Row,
  Col,
  Radio,
  Select,
  Checkbox,
  TimePicker,
} from 'antd';
import axios from 'axios'

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
// const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
const format = 'HH:mm';

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      value: '',
      keyList: [],
      openAddress: false, //是否开启地址预警
      addressList: [''],//预警地址
      openTel: false, //是否开启地址预警
      telList: [''],//预警地址
      //舆情属性
      yqOptions: [
        {label: '全部', value: -1, checked: false},
        {label: '正面', value: 1, checked: false},
        {label: '中性', value: 0, checked: false},
        {label: '负面', value: 2, checked: false},
      ],
      //媒体类型
      mediaOptions: [
        {label: '微博', value: '1'},
        {label: '论坛', value: '2'},
        {label: '新闻', value: '3'},
        {label: '博客', value: '4'},
        {label: '微信', value: '5'},
      ],
      emailSwitch: false,
      alertSwitch: false,
      smsSwitch: false,
      appSwitch: false,
      weekSwitch: false,
    }
  }

  //form 提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        let res = await
          axios.post('vrv-monitor-platform-web/alert/set/update', {
            mode: 1,
            id: this.props.data && this.props.data.id,
            monitorKeyword: this.state.keyList.toString(),
            positiveOrNegative: values.positiveOrNegative,
            webSiteType: values.webSiteType.toString(),
            emailSwitch: this.state.emailSwitch ? '1' : '0',
            alertEmail: this.state.addressList.toString(),
            smsSwitch: this.state.smsSwitch ? '1' : '0',
            smsPhone: this.state.telList.toString(),
            appSwitch: this.state.appSwitch ? '1' : '0',
            weekSwitch: values.weekSwitch ? '1' : '0',
            alertSwitch: this.state.alertSwitch ? '1' : '0',
            frequency: values.frequency,
            monitorStartTime: values.starttime.format('hh:mm'),
            monitorEndTime: values.endtime.format('hh:mm')
          })
        if (res.data.statusCode === 200) {
          this.props.query()
          this.props.hide();
        } else {
          message.error(res.data.message)
        }
      }
    });
  }

  //关键词input change事件
  onChange = (e) => {
    this.setState({value: e.target.value});
  }

  //添加关键词
  addKey = () => {
    if (this.state.value === '') {
      message.warning('不能为空!');
      return;
    } else if (this.state.keyList.indexOf(this.state.value) !== -1) {
      message.warning('该关键词已经存在!');
      return;
    }
    this.setState(prevState => ({
      keyList: [...prevState.keyList, this.state.value]
    }))
    this.setState({
      value: ''
    })
  }

  //关键词删除事件
  deleteKeyById = (key) => {
    this.setState(prevState => ({
      keyList: prevState.keyList.filter((item) => item !== key)
    }))
  }

  //邮箱输入框删除事件
  deleteAddressById = (key) => {
    this.setState(prevState => ({
      addressList: prevState.addressList.filter((item) => item !== key)
    }))
  }

  deleteTelById = (key) => {
    this.setState(prevState => ({
      telList: prevState.telList.filter((item) => item !== key)
    }))
  }

  //新增地址
  addAddress = () => {
    this.setState(
      prevState => ({
        addressList: [...prevState.addressList, '']
      })
    )
  }
  //开启地址预警
  openAddress = (e) => {
    this.setState({
      openAddress: e.target.checked,
      emailSwitch: e.target.checked,
    })
  }
  addressInputChange = (evt, index) => {
    let item = this.state.addressList;
    if (this.state.addressList.indexOf(evt.target.value) !== -1) {
      return message.warning('该邮箱已经存在!');
    }
    item[index] = evt.target.value
    this.setState(prevState => ({
      addressList: item
    }))
  }
  //新增电话
  addTel = () => {
    this.setState(
      prevState => ({
        telList: [...prevState.telList, '']
      })
    )
  }
  //开启地址预警
  openTel = (e) => {
    this.setState({
      openTel: e.target.checked,
      smsSwitch: e.target.checked,
    })
  }

  //电话输入框删除事件
  telInputChange = (evt, index) => {
    if (this.state.telList.indexOf(evt.target.value) !== -1) {
      return message.warning('该号码已经存在!');
    }
    let item = this.state.telList;
    item[index] = evt.target.value
    this.setState(prevState => ({
      telList: item
    }))
  }

  compareToStarttime = (rule, value, callback) => {
    const form = this.props.form;
    if (parseInt(value.format('hh:mm').trim().replace(':',''),10)<=parseInt(form.getFieldValue('starttime').format('hh:mm').trim().replace(':',''),10)) {
      callback('结束时间需大于开始时间!');
    } else {
      callback();
    }
  }


  componentDidMount() {
    if (this.props.data !== {}) {
      let data = this.props.data;
      this.props.form.setFieldsValue({
        positiveOrNegative: data.positiveOrNegative,
        webSiteType: data.webSiteType.split(','),
        frequency: data.frequency,
        weekSwitch: data.weekSwitch,
        starttime: moment(data.monitorStartTime, 'HH:mm'),
        endtime: moment(data.monitorEndTime, 'HH:mm'),
      });
      this.setState({
        keyList: data.monitorKeyword.split(','),
        addressList: data.alertEmail.split(','),
        telList: data.smsPhone.split(','),
        addressSwitch: data.emailSwitch === '1' ? true : false,
        openAddress: data.emailSwitch === '1' ? true : false,
        openTel: data.smsSwitch === '1' ? true : false,
        emailSwitch: data.emailSwitch === '1' ? true : false,
        alertSwitch: data.alertSwitch === '1' ? true : false,
        smsSwitch: data.smsSwitch === '1' ? true : false,
        appSwitch: data.appSwitch === '1' ? true : false,
      })
    }
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 2},
      wrapperCol: {span: 16, offset: 1},
    }
    const buttonLayout = {
      labelCol: {span: 0},
      wrapperCol: {span: 16, offset: 3},
    }

    let addressStyle = {
      display: this.state.openAddress ? 'inline-block' : 'none',
      width: 200,
      marginRight: 10
    }
    let telStyle = {
      display: this.state.openTel ? 'inline-block' : 'none',
      width: 200,
      marginRight: 10
    }
    return (
      <div className="sysWarnopen">
        <Form onSubmit={this.handleSubmit}>
          <div className="head-title">预警条件</div>
          <FormItem
            label="关键词(6)"
            {...formItemLayout}
            style={{marginBottom: '15px'}}
          >
            <Input style={{width: 186}} value={this.state.value} onChange={this.onChange} placeholder="请输入关键词"/>
            <Button type="primary" onClick={this.addKey} style={{marginLeft: 20}}>添加</Button>
          </FormItem>
          <FormItem
            label="">
            <Row type="flex" justify="end">
              <Col span={21} style={{border: '1px solid #e9ebed', height: 57,}}>
                {
                  this.state.keyList.length > 0 ?
                    <ul>
                      {
                        this.state.keyList.map((item, i) => {
                          return <li
                            style={{
                              border: '1px solid #e9ebed',
                              height: '37px',
                              lineHeight: '37px',
                              display: 'inline-block',
                              padding: '0 10px',
                              margin: '10px 0 10px 10px',
                              listStyle: 'none',
                              background: '#ebecee',
                              color: '#30383e'
                            }} key={i}>
                            {item}<Icon type="close" onClick={() => {
                            this.deleteKeyById(item)
                          }} style={{marginLeft: '5px', color: '#30383e'}}/></li>
                        })
                      }
                    </ul> : <div></div>
                }
              </Col>
            </Row>
          </FormItem>
          <FormItem
            label="舆情属性"
            {...formItemLayout}
          >
            {getFieldDecorator('positiveOrNegative')(
              <RadioGroup name="radiogroup">
                <Radio value="-1">全部</Radio>
                <Radio value="1">正面</Radio>
                <Radio value="0">中性</Radio>
                <Radio value="2">负面</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem
            label="媒体类型"
            {...formItemLayout}
          >
            {getFieldDecorator('webSiteType')(
              <Checkbox.Group>
                {
                  this.state.mediaOptions.map((item, i) => {
                    return <Checkbox key={i} value={item.value}>{item.label}</Checkbox>
                  })
                }
              </Checkbox.Group>
            )}
          </FormItem>
          <div className="head-title">预警条件</div>
          <FormItem
            label="预警通知"
            {...formItemLayout}
          >
            {getFieldDecorator('emailSwitch')(
              <Checkbox onChange={this.openAddress} checked={this.state.emailSwitch}>开启预警</Checkbox>
            )}
            <div className="link" onClick={this.addAddress} style={addressStyle}>新增地址</div>
            <br/>
            {
              this.state.addressList.map((address, i) => {
                return <Input style={addressStyle} value={address} key={i} type="email"
                              prefix={<Icon type="close"
                                            style={{color: 'rgba(0,0,0,.25)', position: 'absolute', right: '5px'}}
                                            onClick={() => {
                                              this.deleteAddressById(address)
                                            }}/>}
                              onChange={(evt) => {
                                this.addressInputChange(evt, i)
                              }} placeholder="请输入地址"/>
              })
            }

          </FormItem>
          <FormItem
            label="短信预警"
            {...formItemLayout}
          >
            {getFieldDecorator('smsSwitch')(
              <Checkbox onChange={this.openTel} checked={this.state.smsSwitch}>开启预警</Checkbox>
            )}
            <div className="link" onClick={this.addTel} style={telStyle}>新增号码</div>
            <br/>
            {
              this.state.telList.map((tel, i) => {
                return <Input style={telStyle} value={tel} key={i} type="tel"
                              prefix={<Icon type="close"
                                            style={{color: 'rgba(0,0,0,.25)', position: 'absolute', right: '5px'}}
                                            onClick={() => {
                                              this.deleteTelById(tel)
                                            }}/>} placeholder="请输入号码"
                              onChange={(evt) => {
                                this.telInputChange(evt, i)
                              }}/>
              })
            }
          </FormItem>
          <FormItem
            label="APP预警"
            {...formItemLayout}
          >
            {getFieldDecorator('appSwitch')(
              <Checkbox onChange={(evt) => {
                this.setState({appSwitch: evt.target.value})
              }} checked={this.state.appSwitch}>开启预警</Checkbox>
            )}
          </FormItem>
          <FormItem
            label="WEB预警"
            {...formItemLayout}
          >
            {getFieldDecorator('alertSwitch')(
              <Checkbox onChange={(evt) => {
                this.setState({alertSwitch: evt.target.value})
              }}
                        checked={this.state.alertSwitch}>开启预警</Checkbox>
            )}
          </FormItem>
          <div className="head-title">短信\邮件预警时间设置<span
            style={{color: '#9ba2ab', fontSize: '14px', marginLeft: '10px'}}>(APP预警请进入APP设置)</span>
          </div>
          <FormItem
            label="预警时间"
            {...formItemLayout}
          >
            <Col span={3}>
              <FormItem label={``}>
                {getFieldDecorator(`starttime`, {
                  rules: [{required: true, message: '日期不能为空!'}],
                })(
                  <TimePicker format={format}/>
                )}
              </FormItem>
            </Col>
            <Col span={1} style={{textAlign: 'center'}}>
              To
            </Col>
            <Col span={3}>
              <FormItem label={``}>
                {getFieldDecorator(`endtime`, {
                  rules: [{required: true, message: '日期不能为空!'}, {
                    validator: this.compareToStarttime,
                  }],
                })(
                  <TimePicker format={format}/>
                )}
              </FormItem>
            </Col>
          </FormItem>
          <FormItem
            label="周末预警"
            {...formItemLayout}
          >
            {getFieldDecorator('weekSwitch')(
              <RadioGroup name="radiogroup">
                <Radio value="1">预警</Radio>
                <Radio value="0">不预警</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem
            label="预警频次"
            {...formItemLayout}
          >
            {getFieldDecorator('frequency', {
              rules: [
                {required: true, message: '请选择'},
              ],
            })(
              <Select style={{width: 120}}>
                <Option value="0">5分钟</Option>
                <Option value="1">10分钟</Option>
                <Option value="2">30分钟</Option>
                <Option value="3">1小时</Option>
                <Option value="4">6小时</Option>
                <Option value="5">一天</Option>
              </Select>
            )}

          </FormItem>
          <FormItem {...buttonLayout}>
            <Button type="primary" htmlType="submit">保存</Button>
            <Button style={{marginLeft: '20px'}} onClick={() => {
              this.props.hide()
            }}>取消</Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

const SysWarnopen = Form.create()(App);
export default SysWarnopen